/*
 * 文件名：TwoStackQueue.java
 * 描述： TwoStackQueue.java
 * 修改人：Lo&Wang
 * 修改时间：2016年11月28日
 * 修改内容：新增
 */
package com.lowang.test.queue;

import java.util.Stack;

/**
 * 两个栈实现一个队列，队列先进先出，栈，先进后出。
 * @author zhengmo
 */
public class TwoStackQueue {
    private Stack<Integer> push;
    private Stack<Integer> pop;
    public TwoStackQueue() {
        push = new Stack<>();
        pop = new Stack<>();
    }
    public void add(Integer num) {
        push.push(num);
    }
    public Integer poll() {
        if (pop.isEmpty() && push.isEmpty()) {
            return null;
        }
        if (pop.size() > 0) {
            return pop.pop();
        }
        while (push.size() > 1) {
            pop.add(push.pop());
        }
        return push.pop();
    }
    public Integer peek() {
        if (pop.isEmpty() && push.isEmpty()) {
            return null;
        }
        if (pop.size() > 0) {
            return pop.peek();
        }
        if (push.size() > 0) {
            while (push.size() > 0) {
                pop.push(push.pop());
            }
        }
        return pop.peek();
    }
    public boolean isEmpty() {
        return push.isEmpty() && pop.isEmpty();
    }
    public static void main(String[] args) {
        TwoStackQueue queue = new TwoStackQueue();
        queue.add(2);
        System.out.println(queue.peek());
        queue.add(3);
        System.out.println(queue.peek());
        queue.add(5);
        System.out.println(queue.peek());
        queue.add(1);
        System.out.println(queue.peek());
        System.out.println("=------");
        while (!queue.isEmpty()) {
            System.out.println(queue.peek());
            System.out.println("出:"+queue.poll());
        }
    }
}
